package cn.edu.zafu.bigdata.bd121.studentdb.utils;

import java.lang.reflect.Constructor;
import java.sql.ResultSet;
import java.sql.SQLException;

/**
 * 将数据库返回值转化为类对象
 *
 * @author 202211090121
 */
public class ConvertUtils {

    public static <T> T convert(ResultSet set, Class<T> clazz) {
        try {
            if (set.next()) {
                Constructor<T> constructor = clazz.getConstructor(clazz.getConstructors()[0].getParameterTypes());
                Class<?>[] params = constructor.getParameterTypes();
                Object[] objects = new Object[params.length];
                for (int i = 0; i < params.length; i++) {
                    objects[i] = set.getObject(i + 1);
                    if (objects[i].getClass() != params[i]) {
                        throw new SQLException("错误的接收类型");
                    }
                }
                return constructor.newInstance(objects);
            }
        } catch (Exception e) {
            System.err.println("数据库对象转换异常");
            return null;
        }
        return null;
    }
}
